import { create } from "zustand";

export type memberInfo = {
  teamName: string;
  teamId: number;
  serverIcon: string;
  serverId: number;
  serverName: string;
  memberId: number;
  memberName: string;
};
interface MemberState {
  memberInfo: Array<memberInfo>;
  favoriteList: Record<string, Array<number>>;
  init: () => Promise<void>;
  saveInfo: (info: Array<memberInfo>) => Promise<void>;
  saveFavoriteList: (info: Record<string, Array<number>>) => Promise<void>;
}

export const useMemberStore = create<MemberState>((set) => ({
  memberInfo: [],
  favoriteList: {},
  // 从 storage 初始化仪表盘信息
  init: async () => {
    try {
      const result = await chrome.storage.local.get("memberInfo");
      if (result.memberInfo) {
        set({ memberInfo: result.memberInfo });
      }
      const favoriteResult = await chrome.storage.local.get("favoriteList");
      if (favoriteResult.favoriteList) {
        set({ favoriteList: favoriteResult.favoriteList });
      }
    } catch (error) {
      console.error("Failed to init member info:", error);
    } finally {
    }
  },

  // 保存仪表盘信息到 storage
  saveInfo: async (info: Array<memberInfo>) => {
    try {
      await chrome.storage.local.set({ memberInfo: info });
      set({ memberInfo: info }); // ✅ 正确更新 dashBoardInfo 字段
    } catch (error) {
      console.error("Failed to save member info:", error);
      throw error;
    } finally {
    }
  },
  saveFavoriteList: async (info: Record<string, Array<number>>) => {
    try {
      await chrome.storage.local.set({ favoriteList: info });
      set({ favoriteList: info });
    } catch (error) {
      console.error("Failed to save favorite list:", error);
      throw error;
    }
  },
}));
